package cn.tramy.pinxian.wind.handler

import cn.tramy.pinxian.common.exception.CommonException
import java.lang.reflect.Method

class HandlerInfo<T : Any>(private val instance: Any, private val handlerMethod: Method, val messageType: Class<T>, val afterCommit: Boolean = false) {
    fun canHandle(clazz: Class<*>) = clazz.isAssignableFrom(messageType)
    fun <M : T> handle(message: M) {
        when (this.handlerMethod.parameterCount) {
            1 -> this.handlerMethod.invoke(instance, message)
            0 -> println("No parameter in method: ${this.handlerMethod},IGNORED")
            else -> {
                if (this.handlerMethod.parameterTypes[1] == HandleContext::class.java) {
                    this.handlerMethod.invoke(instance, message, HandleContext.current())
                } else {
                    throw CommonException("Second parameter on Handler Method [${this.handlerMethod.name}] should be HandleContext")
                }
            }
        }
    }

    override fun toString(): String {
        return "HandlerInfo(instance=$instance, handlerMethod=$handlerMethod, messageType=$messageType, afterCommit=$afterCommit)"
    }
}